package com.hmdp.service.impl;


import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    private final ObjectMapper objectMapper = new ObjectMapper();
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryType() {
        String key = CACHE_SHOPTYPE_KEY;
        // 1. 从 redis 查询店铺类型缓存
        String shopTypesJson = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(shopTypesJson)) {
            try {
                // 存在，将 JSON 字符串反序列化为 List<ShopType>
                List<ShopType> shopTypes = objectMapper.readValue(shopTypesJson, new TypeReference<List<ShopType>>() {});
                return Result.ok(shopTypes);
            } catch (Exception e) {
                e.printStackTrace();
                // 反序列化失败，继续查询数据库
            }
        }
        // 2. 不存在，查询数据库
        List<ShopType> shopTypes = query().orderByAsc("sort").list();
        // 3. 判断是否存在
        if (shopTypes == null || shopTypes.isEmpty()) {
            return Result.fail("不存在商铺类型信息！");
        }
        // 4. 存在则保存至 redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shopTypes), CACHE_SHOPTYPE_TTL, TimeUnit.MINUTES);
        return Result.ok(shopTypes);
    }
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
        return BooleanUtil.isTrue(flag); //避免自动拆箱带来的空指针问题
    }

    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }
}
